<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>账号管理</el-breadcrumb-item>
      <el-breadcrumb-item>修改密码</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <div class="box">
        <el-alert
          title="警告"
          type="warning"
          description="如果忘记密码，联系超管修改密码！"
          show-icon
          :closable="false"
        ></el-alert>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
          <el-form-item label="新密码" prop="pass">
            <el-input show-password v-model="ruleForm.pass"></el-input>
          </el-form-item>
          <el-form-item label="重复新密码" prop="checkPass">
            <el-input show-password v-model="ruleForm.checkPass"></el-input>
          </el-form-item>
        </el-form>
        <div class="btn" align="center">
          <el-button type="primary" @click="putpass">修改完成</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        pass: '',
        checkPass: ''
      },
      rules: {
        pass: [{ validator: validatePass, trigger: 'blur' }],
        checkPass: [{ validator: validatePass2, trigger: 'blur' }]
      }
    }
  },
  methods: {
    putpass() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put('password', { password: this.ruleForm.pass })
          if (res.meta.status != 200) {
            return this.$message.error('修改失败！')
          }
          this.$message.success('修改成功！')
          window.sessionStorage.clear()
          this.$router.push('/login')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.box {
  margin: 0 auto;
  width: 700px;
  height: 300px;
}
.el-button {
  display: flex;
  justify-content: center;
}
.btn {
  margin-top: 50px;
}
.el-form {
  margin-top: 40px;
}
</style>